package com.aj.activity;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.RegisterRequest;
import com.aj.http.request.RequestVerificationRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.RegisterResponse;
import com.aj.http.response.RequestVerificationRespons;
import com.aj.utils.Contants;
import com.aj.utils.MobileUtil;

public class EnterVerificationCodeActivity extends BaseActivity {

	public static EnterVerificationCodeActivity instance;

	private Button next;

	private String pageFlag = "";

	private Button resendbutton;

	private EditText verificationcode_enter;

	private boolean isEnter = false;

	private int time = 60;

	private Timer timer;

	private VerificationTimerTask verificationTimerTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_enter_verificationcode);
		initView();
	}

	private void initView() {
		instance = this;
		next = (Button) findViewById(R.id.next);
		resendbutton = (Button) findViewById(R.id.resendbutton);
		verificationcode_enter = (EditText) findViewById(R.id.verificationcode_enter);
		pageFlag = getIntent().getStringExtra(Contants.PAGEFLAG_STRING);
		if (pageFlag != null
				&& pageFlag.equals(Contants.FORGET_PAGEFLAG_STRING)) {
			setActionBarTitle(R.string.forget_title_text);
		} else {
			setActionBarTitle(R.string.register_title_text);
		}
		ClickEvent clickEvent = new ClickEvent();
		next.setOnClickListener(clickEvent);
		resendbutton.setOnClickListener(clickEvent);
	}

	class ClickEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			final Intent intent = null;
			switch (v.getId()) {
			case R.id.next:
				if (verificationcode_enter.getText().toString().trim().length() == 0) {
					Toast.makeText(
							EnterVerificationCodeActivity.this,
							getString(R.string.enter_verificationcode_hinttext),
							Toast.LENGTH_LONG).show();
					return;
				}
				if (verificationcode_enter.getText().toString().trim().length() < 5) {
					Toast.makeText(
							EnterVerificationCodeActivity.this,
							getString(R.string.enter_verificationcode_error_text),
							Toast.LENGTH_LONG).show();
					return;
				}
				if (!isEnter) {
					Toast.makeText(
							EnterVerificationCodeActivity.this,
							getString(R.string.enter_verificationcode_click_error_text),
							Toast.LENGTH_LONG).show();
					return;
				}

				showProgressDialog();
				RegisterRequest registerRequest = new RegisterRequest();

				registerRequest.excute(EnterVerificationCodeActivity.this,
						getIntent().getStringExtra(Contants.PHONEFLAG_STRING),
						verificationcode_enter.getText().toString(),
						MobileUtil.getImei(EnterVerificationCodeActivity.this),
						new IHttpCallBack() {
							@Override
							public void success(String result) {
								dimissProgressDialog();
								try {
									RegisterResponse resopne = new RegisterResponse(
											new JSONObject(result));
									Common common = resopne.getCommon();
									if (common != null) {
										if (common
												.getReturnCode()
												.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
											Intent intent = new Intent(
													Contants.SET_PASSWORD_ACTIVITY_ACTION);
											intent.putExtra(
													Contants.PAGEFLAG_STRING,
													pageFlag);
											intent.putExtra(
													Contants.SMSVALIDATETOKEN_STRING,
													resopne.getSmsValidateToken());
											if (getIntent().hasExtra(
													Contants.PHONEFLAG_STRING)) {
												intent.putExtra(
														Contants.PHONEFLAG_STRING,
														getIntent()
																.getStringExtra(
																		Contants.PHONEFLAG_STRING));
											}
											intent.putExtra(
													Contants.VERIFICATIONFLAG_STRING,
													verificationcode_enter
															.getText()
															.toString().trim());
											startActivity(intent);
										} else {
											Toast.makeText(
													EnterVerificationCodeActivity.this,
													common.getErrorMsg(),
													Toast.LENGTH_LONG).show();
										}
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void fail(String result) {
								dimissProgressDialog();
								try {
									RegisterResponse resopne = new RegisterResponse(
											new JSONObject(result));
									Common common = resopne.getCommon();
									Toast.makeText(
											EnterVerificationCodeActivity.this,
											common.getErrorMsg(),
											Toast.LENGTH_LONG).show();
								} catch (JSONException e) {

								}
							}
						});

				break;
			case R.id.resendbutton:
				isEnter = true;
				disableResendButton();
				initTask();
				RequestVerificationRequest requestVerificationRequest = new RequestVerificationRequest();
				requestVerificationRequest.excute(instance, getIntent()
						.getStringExtra(Contants.PHONEFLAG_STRING),
						new IHttpCallBack() {
							@Override
							public void success(String result) {
								try {
									RequestVerificationRespons respons = new RequestVerificationRespons(
											new JSONObject(result));
									Common common = respons.getCommon();
									if (common != null
											&& common
													.getReturnCode()
													.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
										Toast.makeText(
												EnterVerificationCodeActivity.this,
												getString(R.string.send_message_success_text),
												Toast.LENGTH_LONG).show();
									} else {
										Toast.makeText(
												EnterVerificationCodeActivity.this,
												common.getErrorMsg(),
												Toast.LENGTH_LONG).show();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void fail(String result) {
								try {
									RequestVerificationRespons respons = new RequestVerificationRespons(
											new JSONObject(result));
									Common common = respons.getCommon();
									if (common != null) {
										Toast.makeText(
												EnterVerificationCodeActivity.this,
												common.getErrorMsg(),
												Toast.LENGTH_LONG).show();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});
				break;
			default:
				break;
			}
		}
	}

	private void disableResendButton() {
		resendbutton.setClickable(false);
		resendbutton.setFocusable(false);
		resendbutton.setFocusableInTouchMode(false);
		resendbutton
				.setBackgroundResource(R.drawable.shape_corners_button_disable_click);
	}

	private void enableResendButton() {
		resendbutton.setClickable(true);
		resendbutton.setFocusable(true);
		resendbutton.setFocusableInTouchMode(true);
		resendbutton.requestFocus();
		resendbutton.setBackgroundResource(R.drawable.button_click_selector);
	}

	class VerificationTimerTask extends TimerTask {
		@Override
		public void run() {
			if (time <= 1) {
				handler.sendEmptyMessage(Contants.HANDLER_CANNELHANDLER_INT);
			} else {
				--time;
				handler.sendEmptyMessage(Contants.HANDLER_CHANGEUI_INT);
			}
		}
	}

	private void initTask() {
		if (verificationTimerTask == null) {
			verificationTimerTask = new VerificationTimerTask();
		}
		if (timer == null) {
			timer = new Timer();
		}
		timer.schedule(verificationTimerTask, 0, 1000);
	}

	private void cannelTask() {
		if (verificationTimerTask != null) {
			verificationTimerTask.cancel();
			verificationTimerTask = null;
		}
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (handler != null) {
			handler.removeMessages(Contants.HANDLER_CHANGEUI_INT);
		}
		time = 60;
	}

	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case Contants.HANDLER_CHANGEUI_INT:
				resendbutton.setText(getString(R.string.resend_text) + "("
						+ time + ")");
				break;
			case Contants.HANDLER_CANNELHANDLER_INT:
				cannelTask();
				enableResendButton();
				resendbutton.setText(getString(R.string.resend_text));
				break;
			default:
				break;
			}
			return true;
		}
	});

	@Override
	protected void onStop() {
		super.onStop();
		cannelTask();
	};
}
